package com.lmk.qs.jdbc;


import com.lmk.qs.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 银行转账 jdbc管理事务案例
 */
public class Test07 {
    public static void main(String[] args) {
        //获取数据库连接
        Connection con=null;
        PreparedStatement pr1=null;
        PreparedStatement pr2=null;
        try {
            con= JDBCUtil.getConnection();
            con.setAutoCommit(false);
            String sql1="update account set balance =balance - ? where id=?";
            String sql2="update account set balance = balance + ? where id=?";
            pr1=con.prepareStatement(sql1);
            pr2=con.prepareStatement(sql2);
            pr1.setDouble(1,5000);
            pr1.setInt(2,1);
            pr2.setDouble(1,5000);
            pr2.setInt(2,2);
            pr1.executeUpdate();

            pr2.executeUpdate();
            con.commit();






        } catch (Exception throwables) {
            throwables.printStackTrace();
            try {if(con!=null){
                con.rollback();}
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }finally {
            JDBCUtil.close(pr1,con);
            JDBCUtil.close(pr2,null);
        }
    }
}
